package com.rw;

import com.rw.dao.UserDao;
import com.rw.pojo.User;
import com.rw.service.UserDto;
import com.rw.utils.DataSource;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;


public class TestSpringMybatis {



    @Test
    public void test1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        //获取spring IOC中的所有的bean的id
        String[] names = ac.getBeanDefinitionNames();
        for (String name:names ) {
            System.out.println(name);
        }
    }

    @Test
    public void testLogin(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        UserDao dao = (UserDao) ac.getBean("userDao");
        User u = dao.login("张三", "123");
        System.out.println(u);
    }

    @Test
    public void testTranslate() throws SQLException, ClassNotFoundException {
        DataSource dataSource = new DataSource("jdbc:mysql://localhost:3306/account?useSSL=false&characterEncoding=utf-8","root","123456");
        double money = -200.0;
        int aid = 1;
        dataSource.getConn().setAutoCommit(false);
        String  sql = "UPDATE t_account SET money=money+"+money+" WHERE aid ="+aid;
        dataSource.updateData(sql);
        System.out.println("张三的钱扣费成功");

        double money2 = 200.0;
        int aid2 = 2;
        //给李四账户加钱的时候，出现了异常
        String  sql2 = "UPDATE t_account SET money=money+"+money2+" WHERE aid ="+aid2;;
        dataSource.updateData(sql2);
        if(true){
            //这个位置还有其他的表操作，insert数据
            dataSource.getConn().rollback();
            throw new RuntimeException("1234");

        }
        dataSource.getConn().commit();
        System.out.println("李四的钱增加成功");
        //有很多的转账操作
        dataSource.closed();

    }

    @Test
    public  void testDto(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
        UserDto u = (UserDto) ac.getBean("userDto");
        System.out.println(u);
    }

}
